<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Outlinkrule;
use think\Cache;

class Outlinkdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'outlink_id';

    protected $name = 'outlink';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'outlink_name'
    ];

    public function setOutlinkPicturesAttr($value)
    {
        if ($value) {
            if (is_array($value)) {
                return implode(',', $value);
            } else {
                return $value;
            }
        } else {
            return '';
        }
    }

    protected function setOutlinkNameAttr($value)
    {
        return trim($value);
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeOutlinkName($query, $outlink_name)
    {
        $query->where('outlink_name', 'like', '%' . $outlink_name . '%');
    }

    public function scopeOutlinkCategoryId($query, $outlink_category_id)
    {
        $query->where('outlink_category_id', 'IN', $outlink_category_id);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['outlink_name']) && $this->param['outlink_name'] != '') {
            $query->outlinkName($this->param['outlink_name']);
        }
        if (isset($this->param['outlink_category_id']) && $this->param['outlink_category_id'] != '') {
            $query->outlinkCategoryId($this->param['outlink_category_id']);
        }
    }

    public function ajaxFind($outlink_id = '')
    {
        if ($outlink_id) {
            $this->param['outlink_id'] = $outlink_id;
        }
        $data = $this->useGlobalScope(false)
            ->master()
            ->where('outlink_id', $this->param['outlink_id'])
            ->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
        } else {
            $data = array();
        }
        return $data;
    }

    public function ajaxSelect()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $data = $this->order('outlink_category_id asc,sort asc,outlink_id asc')
            ->cache($this->cache_name('outlink_list'), 86400, 'outlink')
            ->page($this->param['page'], $this->param['limit'])
            ->select();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxCount()
    {
        $count = $this->cache($this->cache_name('outlink_count'), 86400, 'outlink')
            ->count();
        return $count;
    }

    public function ajaxSave()
    {
        $rule = new Outlinkrule();
        $this->param['partner_id'] = PARTNER_ID;
        if (isset($this->param['outlink_id']) && $this->param['outlink_id'] != '') {
            if (! $rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
            unset($this->param['partner_id']);
            $this->save($this->param, [
                'outlink_id' => $this->param['outlink_id']
            ]);
        } else {
            if (! $rule->check($this->param)) {
                return $rule->getError();
            }
            unset($this->param['partner_id']);
            $this->allowField(true)->save($this->param);
        }
        Cache::clear('outlink');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['outlink_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('outlink_id', 'IN', $this->param['outlink_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('outlink_id', 'IN', $this->param['outlink_id']);
                }, true);
            }
            Cache::clear('outlink');
            return 'success';
        }
    }
    // 数据处理
    protected function handleData($val)
    {
        $uploaddb = new Uploaddb();
        $outlinkCategorydb = new OutlinkCategorydb();
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'outlink_category_id':
                    $get_outlink_category = $outlinkCategorydb->ajaxFind($val['outlink_category_id']);
                    $val['outlink_category_name'] = $get_outlink_category['category_name'];
                    break;
                case 'outlink_pictures':
                    if ($val['outlink_pictures']) {
                        $temp = explode(',', $val['outlink_pictures']);
                        $val['outlink_picture'] = $uploaddb->getFind($temp[0]);
                        $val['outlink_pictures'] = $uploaddb->getSelect($temp);
                    }
                    break;
                case 'outlink_intro':
                    $val['outlink_intro_br'] = nl2br($v);
                    break;
                case 'create_time':
                    $val['day'] = date('d', strtotime($v));
                    $val['month'] = date('m', strtotime($v));
                    $val['year'] = date('Y', strtotime($v));
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}